<template>
  <div class="ranking">
    <div class="container">
      <div class="ranking-header">
        <h1 class="page-title">热门排行榜</h1>
        <p class="page-description">
          发现最受欢迎的故事和创作者
        </p>
      </div>

      <!-- Ranking Tabs -->
      <div class="ranking-tabs">
        <button
          v-for="tab in rankingTabs"
          :key="tab.key"
          @click="activeTab = tab.key"
          :class="{ active: activeTab === tab.key }"
          class="ranking-tab"
        >
          <component :is="tab.icon" :size="18" />
          <span>{{ tab.label }}</span>
        </button>
      </div>

      <!-- Time Period Filter -->
      <div class="time-filter">
        <div class="filter-group">
          <label class="filter-label">时间范围</label>
          <select v-model="timePeriod" class="filter-select">
            <option value="today">今日</option>
            <option value="week">本周</option>
            <option value="month">本月</option>
            <option value="all">全部</option>
          </select>
        </div>
      </div>

      <!-- Ranking Content -->
      <div class="ranking-content">
        <!-- Stories Ranking -->
        <div v-if="activeTab === 'stories'" class="ranking-section">
          <div class="ranking-list">
            <div
              v-for="(story, index) in rankedStories"
              :key="story.id"
              class="ranking-item"
              @click="goToStory(story.id)"
            >
              <div class="rank-number" :class="getRankClass(index)">
                <span v-if="index < 3" class="rank-medal">
                  <Trophy v-if="index === 0" :size="24" />
                  <Award v-else-if="index === 1" :size="24" />
                  <Medal v-else :size="24" />
                </span>
                <span v-else class="rank-text">{{ index + 1 }}</span>
              </div>

              <div class="story-info">
                <h3 class="story-title">{{ story.title }}</h3>
                <div class="story-meta">
                  <span class="story-author">
                    <User :size="14" />
                    {{ story.author_name || story.author }}
                  </span>
                  <span class="story-category">{{ story.category }}</span>
                </div>
                <p class="story-excerpt">{{ getExcerpt(story.content) }}</p>
              </div>

              <div class="story-stats">
                <div class="stat-item">
                  <Eye :size="16" />
                  <span>{{ formatNumber(story.views) }}</span>
                </div>
                <div class="stat-item">
                  <Heart :size="16" />
                  <span>{{ story.likes }}</span>
                </div>
                <div class="stat-item">
                  <MessageCircle :size="16" />
                  <span>{{ story.comments_count || story.comments?.length || 0 }}</span>
                </div>
              </div>

              <div class="trend-indicator">
                <TrendingUp :size="16" class="trend-up" />
              </div>
            </div>
          </div>
        </div>

        <!-- Authors Ranking -->
        <div v-else-if="activeTab === 'authors'" class="ranking-section">
          <div class="ranking-list">
            <div
              v-for="(author, index) in rankedAuthors"
              :key="author.name"
              class="ranking-item author-item"
            >
              <div class="rank-number" :class="getRankClass(index)">
                <span v-if="index < 3" class="rank-medal">
                  <Trophy v-if="index === 0" :size="24" />
                  <Award v-else-if="index === 1" :size="24" />
                  <Medal v-else :size="24" />
                </span>
                <span v-else class="rank-text">{{ index + 1 }}</span>
              </div>

              <div class="author-info">
                <div class="author-avatar">
                  <User :size="24" />
                </div>
                <div class="author-details">
                  <h3 class="author-name">{{ author.name }}</h3>
                  <div class="author-stats">
                    <span>{{ author.storiesCount }} 篇故事</span>
                    <span>{{ formatNumber(author.totalViews) }} 总阅读</span>
                    <span>{{ author.totalLikes }} 总点赞</span>
                  </div>
                </div>
              </div>

              <div class="author-badge">
                <Crown :size="20" />
              </div>
            </div>
          </div>
        </div>

        <!-- Categories Ranking -->
        <div v-else-if="activeTab === 'categories'" class="ranking-section">
          <div class="category-grid">
            <div
              v-for="(category, index) in rankedCategories"
              :key="category.name"
              class="category-card card"
            >
              <div class="category-rank">
                <span class="rank-badge">#{{ index + 1 }}</span>
              </div>
              
              <div class="category-info">
                <h3 class="category-name">{{ category.name }}</h3>
                <div class="category-stats">
                  <div class="stat">
                    <BookOpen :size="16" />
                    <span>{{ category.storiesCount }} 篇故事</span>
                  </div>
                  <div class="stat">
                    <Eye :size="16" />
                    <span>{{ formatNumber(category.totalViews) }} 阅读</span>
                  </div>
                  <div class="stat">
                    <Heart :size="16" />
                    <span>{{ category.totalLikes }} 点赞</span>
                  </div>
                </div>
              </div>

              <div class="category-progress">
                <div class="progress-bar">
                  <div 
                    class="progress-fill"
                    :style="{ width: `${category.percentage}%` }"
                  ></div>
                </div>
                <span class="progress-text">{{ category.percentage }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Achievement Showcase -->
      <div class="achievement-section">
        <h2>本周成就</h2>
        <div class="achievement-grid">
          <div class="achievement-card card">
            <div class="achievement-icon">
              <Zap :size="32" />
            </div>
            <div class="achievement-info">
              <h3>创作之星</h3>
              <p>本周发布故事最多的创作者</p>
              <div class="achievement-winner">
                <User :size="16" />
                <span>{{ topAuthor }}</span>
              </div>
            </div>
          </div>

          <div class="achievement-card card">
            <div class="achievement-icon">
              <Flame :size="32" />
            </div>
            <div class="achievement-info">
              <h3>人气王者</h3>
              <p>本周获得点赞最多的故事</p>
              <div class="achievement-winner">
                <BookOpen :size="16" />
                <span>{{ mostLikedStory }}</span>
              </div>
            </div>
          </div>

          <div class="achievement-card card">
            <div class="achievement-icon">
              <Target :size="32" />
            </div>
            <div class="achievement-info">
              <h3>话题之王</h3>
              <p>本周评论最多的故事</p>
              <div class="achievement-winner">
                <MessageCircle :size="16" />
                <span>{{ mostCommentedStory }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStoriesStore } from '../stores/stories'
import { gsap } from 'gsap'
import {
  Trophy,
  Medal,
  Star,
  Users,
  BookOpen,
  Crown,
  Zap,
  Flame,
  Target,
  Award,
  User,
  Eye,
  Heart,
  MessageCircle,
  TrendingUp
} from 'lucide-vue-next'

const router = useRouter()
const storiesStore = useStoriesStore()

const activeTab = ref('stories')
const timePeriod = ref('week')

const rankingTabs = ref([
  { key: 'stories', label: '故事排行', icon: BookOpen },
  { key: 'authors', label: '作者排行', icon: Users },
  { key: 'categories', label: '分类排行', icon: Star }
])

const rankedStories = computed(() => {
  return storiesStore.publishedStories
    .sort((a, b) => (b.likes + b.views * 0.1) - (a.likes + a.views * 0.1))
    .slice(0, 10)
})

const rankedAuthors = computed(() => {
  const authorsMap = new Map()
  
  storiesStore.publishedStories.forEach(story => {
    const authorName = story.author_name || story.author
    if (!authorsMap.has(authorName)) {
      authorsMap.set(authorName, {
        name: authorName,
        storiesCount: 0,
        totalViews: 0,
        totalLikes: 0
      })
    }
    
    const author = authorsMap.get(authorName)
    author.storiesCount++
    author.totalViews += story.views || 0
    author.totalLikes += story.likes || 0
  })
  
  return Array.from(authorsMap.values())
    .sort((a, b) => (b.totalLikes + b.totalViews * 0.1) - (a.totalLikes + a.totalViews * 0.1))
    .slice(0, 10)
})

const rankedCategories = computed(() => {
  const categoriesMap = new Map()
  let totalStories = 0
  
  storiesStore.publishedStories.forEach(story => {
    totalStories++
    if (!categoriesMap.has(story.category)) {
      categoriesMap.set(story.category, {
        name: story.category,
        storiesCount: 0,
        totalViews: 0,
        totalLikes: 0
      })
    }
    
    const category = categoriesMap.get(story.category)
    category.storiesCount++
    category.totalViews += story.views
    category.totalLikes += story.likes
  })
  
  return Array.from(categoriesMap.values())
    .map(category => ({
      ...category,
      percentage: Math.round((category.storiesCount / totalStories) * 100)
    }))
    .sort((a, b) => b.storiesCount - a.storiesCount)
})

// 本周成就数据
const topAuthor = computed(() => {
  if (rankedAuthors.value.length > 0) {
    return rankedAuthors.value[0].name
  }
  return '暂无数据'
})

const mostLikedStory = computed(() => {
  const stories = [...storiesStore.publishedStories].sort((a, b) => (b.likes || 0) - (a.likes || 0))
  return stories.length > 0 ? stories[0].title : '暂无数据'
})

const mostCommentedStory = computed(() => {
  const stories = [...storiesStore.publishedStories].sort((a, b) => 
    (b.comments_count || b.comments?.length || 0) - (a.comments_count || a.comments?.length || 0)
  )
  return stories.length > 0 ? stories[0].title : '暂无数据'
})

const getRankClass = (index) => {
  if (index === 0) return 'rank-gold'
  if (index === 1) return 'rank-silver'
  if (index === 2) return 'rank-bronze'
  return 'rank-normal'
}

const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const getExcerpt = (content) => {
  return content.length > 80 ? content.substring(0, 80) + '...' : content
}

const goToStory = (storyId) => {
  router.push(`/story/${storyId}`)
}

onMounted(async () => {
  // 加载故事数据
  try {
    await storiesStore.loadStories({
      status: 'published',
      page: 1,
      page_size: 100
    })
  } catch (error) {
    console.error('加载故事失败:', error)
  }
  
  // Animate ranking items
  gsap.fromTo('.ranking-item',
    { opacity: 0, x: -30 },
    {
      opacity: 1,
      x: 0,
      duration: 0.6,
      stagger: 0.1,
      ease: 'power2.out'
    }
  )
  
  gsap.fromTo('.category-card',
    { opacity: 0, y: 30 },
    {
      opacity: 1,
      y: 0,
      duration: 0.6,
      stagger: 0.1,
      ease: 'power2.out'
    }
  )
})
</script>

<style scoped>
.ranking {
  padding: var(--spacing-2xl) 0;
  min-height: 100vh;
}

.ranking-header {
  text-align: center;
  margin-bottom: var(--spacing-3xl);
}

.page-title {
  font-size: var(--font-size-3xl);
  margin-bottom: var(--spacing-md);
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
  max-width: 600px;
  margin: 0 auto;
}

.ranking-tabs {
  display: flex;
  justify-content: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-2xl);
  flex-wrap: wrap;
}

.ranking-tab {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-md) var(--spacing-xl);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-weight: 500;
}

.ranking-tab.active,
.ranking-tab:hover {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.time-filter {
  display: flex;
  justify-content: center;
  margin-bottom: var(--spacing-2xl);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.filter-label {
  font-weight: 500;
  color: var(--text-primary);
}

.filter-select {
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-primary);
}

.ranking-content {
  margin-bottom: var(--spacing-3xl);
}

.ranking-list {
  max-width: 800px;
  margin: 0 auto;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-xl);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  margin-bottom: var(--spacing-lg);
  cursor: pointer;
  transition: all var(--transition-normal);
}

.ranking-item:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-xl);
}

.rank-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  font-weight: 700;
  font-size: var(--font-size-lg);
}

.rank-gold {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #8b5a00;
}

.rank-silver {
  background: linear-gradient(135deg, #c0c0c0, #e5e5e5);
  color: #666;
}

.rank-bronze {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #5d4e37;
}

.rank-normal {
  background: var(--bg-tertiary);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
}

.rank-medal {
  color: inherit;
}

.story-info {
  flex: 1;
}

.story-title {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
}

.story-meta {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

.story-author {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.story-category {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.story-excerpt {
  color: var(--text-secondary);
  line-height: 1.5;
  margin: 0;
}

.story-stats {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.trend-indicator {
  color: var(--success-color);
}

.author-item {
  cursor: default;
}

.author-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  flex: 1;
}

.author-avatar {
  width: 60px;
  height: 60px;
  background: var(--bg-tertiary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
}

.author-details {
  flex: 1;
}

.author-name {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
}

.author-stats {
  display: flex;
  gap: var(--spacing-lg);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.author-badge {
  color: var(--warning-color);
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-xl);
  max-width: 1000px;
  margin: 0 auto;
}

.category-card {
  position: relative;
}

.category-rank {
  position: absolute;
  top: var(--spacing-md);
  right: var(--spacing-md);
}

.rank-badge {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-lg);
  font-size: var(--font-size-sm);
  font-weight: 600;
}

.category-info {
  margin-bottom: var(--spacing-lg);
}

.category-name {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-primary);
  font-size: var(--font-size-xl);
}

.category-stats {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.stat {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.category-progress {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-sm);
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--gradient-primary);
  transition: width var(--transition-normal);
}

.progress-text {
  font-size: var(--font-size-sm);
  font-weight: 500;
  color: var(--text-primary);
}

.achievement-section {
  margin-top: var(--spacing-3xl);
}

.achievement-section h2 {
  text-align: center;
  margin-bottom: var(--spacing-2xl);
  color: var(--text-primary);
}

.achievement-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-xl);
}

.achievement-card {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-xl);
}

.achievement-icon {
  width: 60px;
  height: 60px;
  background: var(--gradient-primary);
  border-radius: var(--radius-xl);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.achievement-info h3 {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
}

.achievement-info p {
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-md) 0;
  font-size: var(--font-size-sm);
}

.achievement-winner {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--primary-color);
  font-weight: 500;
  font-size: var(--font-size-sm);
}

/* Mobile Styles */
@media (max-width: 768px) {
  .ranking-item {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .story-stats {
    flex-direction: row;
    justify-content: center;
  }

  .author-info {
    flex-direction: column;
    text-align: center;
  }

  .author-stats {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .achievement-card {
    flex-direction: column;
    text-align: center;
  }
}
</style>
